package com.tecklab.demo.redis;

import com.tecklab.demo.utils.LogConsolehUtils;
import org.redisson.Redisson;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

public class RedissonBloomFilterDemo {

    public static void main(String[] args) {
        // 关闭日志框架日志打印
        LogConsolehUtils.setInfoLevel();
        // 配置 Redis 连接
        Config config = new Config();
        config.useSingleServer().setAddress("redis://127.0.0.1:6379").setDatabase(0);

        // 初始化 Redisson 客户端
        RedissonClient redisson = Redisson.create(config);

        // 创建布隆过滤器实例
        RBloomFilter<String> bloomFilter = redisson.getBloomFilter("bloomFilter");

        int capacity = 10000;
        long startTime = System.currentTimeMillis();
        // 初始化布隆过滤器，预计元素数量和期望的误判率
        bloomFilter.tryInit(capacity, 0.01); // 预计存储1百万个元素，误判率为1%
        for (int i = 0; i < capacity; i++) {
            bloomFilter.add(String.valueOf(i));
        }
        System.out.printf("初始化布隆过滤器，元素个数: %d, Time taken: %d 毫秒 \n", capacity, System.currentTimeMillis() - startTime);
        
        // 添加元素到布隆过滤器
        bloomFilter.add("example");

         startTime = System.currentTimeMillis();
        boolean exists = bloomFilter.contains("example");
        System.out.printf("Element 'example' in bloom filter: %b, Time taken: %d 毫秒", exists, System.currentTimeMillis() - startTime);

        // 清理资源
        bloomFilter.delete();
        redisson.shutdown();
    }
}